package top.haijunit.common.web.utils;

import lombok.experimental.UtilityClass;
import lombok.extern.slf4j.Slf4j;

import java.net.Inet4Address;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;

/**
 * 本地IP地址和Mac地址
 *
 * @author zhanghaijun
 * @date 2024/4/21 10:12
 * @description [一句话描述该类的功能]
 */
@Slf4j
@UtilityClass
public class LocalIpUtils {
    public static String getIpAddress() {
        String IP = null;
        try {
            InetAddress ip4 = Inet4Address.getLocalHost();
            IP = ip4.getHostAddress();
            log.debug("getIpAddress() IP:{}", ip4.getHostAddress());
        } catch (Exception ignored) {
        }
        return IP;
    }

    public static String getMacAddress() {
        String mac = null;
        try {
            InetAddress ip4 = Inet4Address.getLocalHost();
            mac = getLocalMac(ip4);
            log.debug("getMacAddress() mac:{}", mac);
        } catch (Exception ignored) {
        }
        return mac;
    }

    private static String getLocalMac(InetAddress ip) {
        StringBuilder macStr = new StringBuilder("00-00-00-00-00-00");
        try {
            NetworkInterface networkInterface = NetworkInterface.getByInetAddress(ip);
            byte[] mac = networkInterface.getHardwareAddress();
            if (mac != null && mac.length > 0) {
                macStr = new StringBuilder();
                for (int i = 0; i < mac.length; i++) {
                    if (i != 0) {
                        macStr.append("-");
                    }
                    int temp = mac[i] & 0xFF;
                    macStr.append(Integer.toHexString(temp));
                }
            }
        } catch (SocketException ignored) {
        }
        return macStr.toString();
    }
}
